/*
 * @Descripttion:
 * @version:
 * @Author: pyq
 * @Date: 2024-10-16 21:57:24
 * @LastEditors: pyq
 * @LastEditTime: 2024-10-16 23:03:14
 */

import User from "../models/user.js";
import { successResponse, errorResponse } from "../utils/responseHelper.js";
import getRedisClient from "../utils/redisClient.js";
import bcrypt from "bcrypt";
// import { v4 as uuidv4 } from 'uuid'; // 引入 uuid 库
import axios from "axios";

// 用户注册
export const registerService = async (ctx) => {
  const { username, password } = ctx.request.body;

  // 校验验证码
  // const codeRes = await redis.get(`sms_code_${phone}`);
  // if (!codeRes) {
  //     errorResponse(ctx, 400, "请获取验证码");
  //     return;
  // }

  // if (codeRes !== code) {
  //     errorResponse(ctx, 400, "验证码不正确");
  //     return;
  // }

  // 加密密码
  const passwordHash = await bcrypt.hash(password, 10);

  // 创建用户
  const user = await User.create({
    username,
    password_hash: passwordHash,
  });

  // // 生成 Token
  // const token = uuidv4().replace(/-/g, '');
  // const tokenKey = `user:${token}`;

  // // 存储 Token 到 Redis，并设置过期时间为1小时
  // await redis.set(tokenKey, JSON.stringify(user), { EX: 3600 });

  // 返回成功响应，并返回 token
  const data = { user };
  return successResponse(ctx, data);
};

// 用户登录
export const loginService = async (ctx) => {
  const { username, password } = ctx.request.body;
  // const redis = await getRedisClient();

  // 验证输入数据是否齐全
  if (!username || !password) {
    errorResponse(ctx, 400, "用户名和密码不能为空");
    return;
  }

  // 检查用户是否存在
  const user = await User.findOne({ where: { username } });
  if (!user) {
    errorResponse(ctx, 400, "用户不存在");
    return;
  }

  const isPasswordValid = await bcrypt.compare(password, user.password_hash);
  if (!isPasswordValid) {
    errorResponse(ctx, 400, "密码不正确");
    return;
  }
  // const token = uuidv4().replace(/-/g, '');
  // const tokenKey = `user:${token}`;
  // await redis.set(tokenKey, JSON.stringify(user), {
  //     EX: 60 * 60,
  // });
  const data = {
    username,
  };
  return successResponse(ctx, data);
};

// 发送验证码的函数
const sendSms = async (phone, code) => {
  const host = "https://zwp.market.alicloudapi.com";
  const path = "/sms/sendv2";
  const appcode = "3aaa729971b742c2aeda8eb7fde7d429"; // 替换为你的AppCode
  const headers = {
    Authorization: `APPCODE ${appcode}`,
  };

  const query = {
    mobile: phone,
    content: `【智能云】您的验证码是${code}。如非本人操作，请忽略本短信`,
  };

  try {
    const response = await axios.get(host + path, {
      headers: headers,
      params: query,
    });
    return response.data;
  } catch (error) {
    console.error("短信发送失败:", error.response.data || error.message);
    errorResponse(ctx, 500, "短信发送失败");
    return null;
  }
};

// 发送验证码
export const codeService = async (ctx) => {
  const redisClient = await getRedisClient();
  // 生成随机验证码
  const generateCode = () => Math.floor(1000 + Math.random() * 9000).toString();

  const { phone } = ctx.request.body;

  // 验证电话号码是否有效
  if (!phone) {
    return errorResponse(ctx, 400, "手机号不能为空");
  }

  // 检查是否已经发送验证码
  let code = await redisClient.get(`sms_code_${phone}`);
  if (code) {
    return successResponse(ctx, phone, "验证码已发送，请稍候");
  }

  code = generateCode(); // 生成验证码

  // 将验证码存储到 Redis，并设置5分钟过期时间
  await redisClient.set(`sms_code_${phone}`, code, {
    EX: 300,
  }); // 300秒 = 5分钟

  // 发送验证码短信
  const smsResponse = await sendSms(phone, code);
  if (smsResponse && smsResponse.error_code === 0) {
    return successResponse(ctx, phone, "发送成功");
  }

  return errorResponse(ctx, 400, "短信发送失败");
};
